<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>手撕AVL树 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第十五篇博客–手撕AVL树 BSTBINARY SEARCH TREE二叉查找树，代表树中节点为有序存储所有节点都相同满足以下条件之一1.左子节点值大于等于根节点值且右子节点值小于根节点值2.左子节点值小于等于根节点值且右子节点值大于根节点值的二叉树即位二叉查找树AVL average BST 是一棵平衡的二叉查找树，通过平衡使得单次查找的时间复杂度不会超过logn AVL T">
<meta property="og:type" content="article">
<meta property="og:title" content="手撕AVL树">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/03/31/手撕AVL树/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第十五篇博客–手撕AVL树 BSTBINARY SEARCH TREE二叉查找树，代表树中节点为有序存储所有节点都相同满足以下条件之一1.左子节点值大于等于根节点值且右子节点值小于根节点值2.左子节点值小于等于根节点值且右子节点值大于根节点值的二叉树即位二叉查找树AVL average BST 是一棵平衡的二叉查找树，通过平衡使得单次查找的时间复杂度不会超过logn AVL T">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://eetal.gitee.io/blog/images/avl-tree/r-normal.jpg">
<meta property="og:image" content="http://eetal.gitee.io/blog/images/avl-tree/r2.jpg">
<meta property="og:image" content="http://eetal.gitee.io/blog/images/avl-tree/r3.jpg">
<meta property="og:updated_time" content="2019-03-31T09:31:47.566Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手撕AVL树">
<meta name="twitter:description" content="欢迎查看Eetal的第十五篇博客–手撕AVL树 BSTBINARY SEARCH TREE二叉查找树，代表树中节点为有序存储所有节点都相同满足以下条件之一1.左子节点值大于等于根节点值且右子节点值小于根节点值2.左子节点值小于等于根节点值且右子节点值大于根节点值的二叉树即位二叉查找树AVL average BST 是一棵平衡的二叉查找树，通过平衡使得单次查找的时间复杂度不会超过logn AVL T">
<meta name="twitter:image" content="http://eetal.gitee.io/blog/images/avl-tree/r-normal.jpg">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-手撕AVL树" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/03/31/手撕AVL树/" class="article-date">
  	<time datetime="2019-03-31T08:30:48.042Z" itemprop="datePublished">2019-03-31</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      手撕AVL树
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第十五篇博客–手撕AVL树</p>
<h2 id="BST"><a href="#BST" class="headerlink" title="BST"></a>BST</h2><p>BINARY SEARCH TREE二叉查找树，代表树中节点为有序存储<br>所有节点都相同满足以下条件之一<br>1.左子节点值大于等于根节点值且右子节点值小于根节点值<br>2.左子节点值小于等于根节点值且右子节点值大于根节点值<br>的二叉树即位二叉查找树<br>AVL average BST 是一棵平衡的二叉查找树，通过平衡使得单次查找的时间复杂度不会超过logn</p>
<h2 id="AVL-Tree"><a href="#AVL-Tree" class="headerlink" title="AVL Tree"></a>AVL Tree</h2><p>平衡树的特点是，任意一个节点，其左子树的高度与右子树的高度差保持在1以内（包括1）<br>当出现高度差超过1的子树则进行旋转来调整，旋转时不破坏有序</p>
<h2 id="旋转"><a href="#旋转" class="headerlink" title="旋转"></a>旋转</h2><h3 id="右旋转"><a href="#右旋转" class="headerlink" title="右旋转"></a>右旋转</h3><p>假设左边过高（一般这种过高表现为高度差为2，因为我们应在每次进行插入和删除时旋转进行维护，所以不会出现高度差为3的情况）<br><img src="/blog/images/avl-tree/r-normal.jpg" alt="普通右旋"><br>这时我们通过这种右旋转可以把左边过高子树的一个节点提上来，使得左子树节点高度-1，右子树节点高度+1<br>伪代码就是<br>parent = 要旋转的节点<br>将parent的左节点断开，再将断开的左节点的右子树断开，重新接到parent，作为parent新的左子树<br>将parent从他父亲断开，将parent作为他原来的左子节点（被断开的左子节点）的右子树<br>最后将parent原来的父亲作为此时parent新的父节点（原来的左子节点）的父亲（就是交换位置）</p>
<p>代码实现<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public Node rightTransformAndReturn(Node node) &#123;</span><br><span class="line">	System.out.println(<span class="string">"right transform"</span>);</span><br><span class="line">	Node left = node.leftChild;</span><br><span class="line">	Node leftRightChild = left.rightChild;</span><br><span class="line">	<span class="keyword">if</span>(leftRightChild!=null) &#123;</span><br><span class="line">		leftRightChild.parent = node;</span><br><span class="line">		leftRightChild.status = LEFTSTATUS;</span><br><span class="line">	&#125;</span><br><span class="line">	node.leftChild = leftRightChild;</span><br><span class="line">	left.rightChild = node;</span><br><span class="line">	left.parent = node.parent;</span><br><span class="line">	node.parent = left;</span><br><span class="line">	left.status = node.status;</span><br><span class="line">	<span class="keyword">if</span>(node.status == LEFTSTATUS) &#123;</span><br><span class="line">		left.parent.leftChild = left;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(node.status == RIGHTSTATUS)&#123;</span><br><span class="line">		left.parent.rightChild = left;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		root = left;</span><br><span class="line">	&#125;</span><br><span class="line">	node.status = RIGHTSTATUS;</span><br><span class="line">	<span class="keyword">while</span>(node!=null) &#123;</span><br><span class="line">		node.height = Math.max(getHeight(node.leftChild)+1, getHeight(node.rightChild)+1);</span><br><span class="line">		node = node.parent;</span><br><span class="line">	&#125;</span><br><span class="line">	node = left;</span><br><span class="line">	<span class="built_in">return</span> node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面只分析了第一种情况，有时左子树会是这样<br><img src="/blog/images/avl-tree/r2.jpg" alt="特殊右旋"><br>这时如果按照第一种的做法，此时最终结果会使得右子树高于左子树导致不平衡<br>原因是第一步里有 这一步</p>
<h5 id="将parent的左节点断开，再将断开的左节点的右子树断开，重新接到parent，作为parent新的左子树"><a href="#将parent的左节点断开，再将断开的左节点的右子树断开，重新接到parent，作为parent新的左子树" class="headerlink" title="将parent的左节点断开，再将断开的左节点的右子树断开，重新接到parent，作为parent新的左子树"></a>将parent的左节点断开，再将断开的左节点的右子树断开，重新接到parent，作为parent新的左子树</h5><p>这一步是为了保证其有序不被破坏，所以从断开的是其左节点的右子树，也就是这颗右子树高度是不变的<br>而后右子树又会链接到parent，如果导致树高的不平衡是这颗右子树造成，则旋转后其仍是不平衡的（因为左边减少的高度1实际是左子树的高度）</p>
<p>于是我们得想办法把他变回第一种情况，做法就是，先使用左旋转其parent的左子树，将其变为下图<br><img src="/blog/images/avl-tree/r3.jpg" alt="特殊右旋"><br>这时就可以使用第一种情况的方法来应对了<br>至于为什么只要一次右旋转因为一开始我们就讲过，高度差不会超过2，那平衡的子树的左右结点高度差就不会超过1</p>
<h3 id="左旋转"><a href="#左旋转" class="headerlink" title="左旋转"></a>左旋转</h3><p>此处就是右旋转的镜像实现，就不过多阐述</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">public Node leftTransformAndReturn(Node node) &#123;</span><br><span class="line">	System.out.println(<span class="string">"left transform"</span>);</span><br><span class="line">	Node right = node.rightChild;</span><br><span class="line">	Node rightLeftChild = right.leftChild;</span><br><span class="line">	<span class="keyword">if</span>(rightLeftChild!=null) &#123;</span><br><span class="line">		rightLeftChild.parent = node;</span><br><span class="line">		rightLeftChild.status = RIGHTSTATUS;</span><br><span class="line">	&#125;</span><br><span class="line">	node.rightChild = rightLeftChild;</span><br><span class="line">	right.leftChild = node;</span><br><span class="line">	right.parent = node.parent;</span><br><span class="line">	node.parent = right;</span><br><span class="line">	right.status = node.status;</span><br><span class="line">	<span class="keyword">if</span>(node.status == LEFTSTATUS) &#123;</span><br><span class="line">		right.parent.leftChild = right;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(node.status == RIGHTSTATUS)&#123;</span><br><span class="line">		right.parent.rightChild = right;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> &#123;</span><br><span class="line">		root = right;</span><br><span class="line">	&#125;</span><br><span class="line">	node.status = LEFTSTATUS;</span><br><span class="line">	<span class="keyword">while</span>(node!=null) &#123;</span><br><span class="line">		node.height = Math.max(getHeight(node.leftChild)+1, getHeight(node.rightChild)+1);</span><br><span class="line">		node = node.parent;</span><br><span class="line">	&#125;</span><br><span class="line">	node = right;</span><br><span class="line">	<span class="built_in">return</span> node;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="最终代码"><a href="#最终代码" class="headerlink" title="最终代码"></a>最终代码</h3><p>我们将上方阐述的特殊情况（左旋转的可以联想都是对应的）总结，把对于两种情况的处理都封装<br>使用递归实现<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">public class AVLTree &#123;</span><br><span class="line"></span><br><span class="line">	Node root;</span><br><span class="line">	static final int LEFTSTATUS = 0;</span><br><span class="line">	static final int RIGHTSTATUS = 1;</span><br><span class="line"></span><br><span class="line">	static class Node&#123;</span><br><span class="line">		int num;</span><br><span class="line">		Node leftChild;</span><br><span class="line">		Node rightChild;</span><br><span class="line">		Node parent;</span><br><span class="line">		int height = 0;</span><br><span class="line">		int status = -1;//root</span><br><span class="line">		@Override</span><br><span class="line">		public String <span class="function"><span class="title">toString</span></span>() &#123;</span><br><span class="line">			<span class="built_in">return</span> num+<span class="string">",height["</span>+height+<span class="string">"]-&gt;left["</span>+(leftChild==null?<span class="string">"null"</span>:leftChild.num)+<span class="string">"],-&gt;right["</span>+(rightChild==null?<span class="string">"null"</span>:rightChild.num)+<span class="string">"]"</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	public void printTree(Node parent) &#123;</span><br><span class="line">		<span class="keyword">if</span>(parent!=null) &#123;</span><br><span class="line">			System.out.println(parent);</span><br><span class="line">			printTree(parent.leftChild);</span><br><span class="line">			printTree(parent.rightChild);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	//注意，左旋右旋会改变原来的父节点位置的节点(包括root)</span><br><span class="line">	public Node leftTransformAndReturn(Node node) &#123;</span><br><span class="line">		System.out.println(<span class="string">"left transform"</span>);</span><br><span class="line">		Node right = node.rightChild;</span><br><span class="line">		//双旋转</span><br><span class="line">		<span class="keyword">if</span>(getHeight(right.leftChild)&gt;getHeight(right.rightChild)) &#123;</span><br><span class="line">			rightTransformAndReturn(right);</span><br><span class="line">		&#125;</span><br><span class="line">		Node rightLeftChild = right.leftChild;</span><br><span class="line">		<span class="keyword">if</span>(rightLeftChild!=null) &#123;</span><br><span class="line">			rightLeftChild.parent = node;</span><br><span class="line">			rightLeftChild.status = RIGHTSTATUS;</span><br><span class="line">		&#125;</span><br><span class="line">		node.rightChild = rightLeftChild;</span><br><span class="line">		right.leftChild = node;</span><br><span class="line">		right.parent = node.parent;</span><br><span class="line">		node.parent = right;</span><br><span class="line">		right.status = node.status;</span><br><span class="line">		<span class="keyword">if</span>(node.status == LEFTSTATUS) &#123;</span><br><span class="line">			right.parent.leftChild = right;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(node.status == RIGHTSTATUS)&#123;</span><br><span class="line">			right.parent.rightChild = right;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			root = right;</span><br><span class="line">		&#125;</span><br><span class="line">		node.status = LEFTSTATUS;</span><br><span class="line">		<span class="keyword">while</span>(node!=null) &#123;</span><br><span class="line">			node.height = Math.max(getHeight(node.leftChild)+1, getHeight(node.rightChild)+1);</span><br><span class="line">			node = node.parent;</span><br><span class="line">		&#125;</span><br><span class="line">		node = right;</span><br><span class="line">		<span class="built_in">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line">	public Node rightTransformAndReturn(Node node) &#123;</span><br><span class="line">		System.out.println(<span class="string">"right transform"</span>);</span><br><span class="line">		Node left = node.leftChild;</span><br><span class="line">		//双旋转</span><br><span class="line">		<span class="keyword">if</span>(getHeight(left.rightChild)&gt;getHeight(left.leftChild)) &#123;</span><br><span class="line">			leftTransformAndReturn(left);</span><br><span class="line">		&#125;</span><br><span class="line">		Node leftRightChild = left.rightChild;</span><br><span class="line">		<span class="keyword">if</span>(leftRightChild!=null) &#123;</span><br><span class="line">			leftRightChild.parent = node;</span><br><span class="line">			leftRightChild.status = LEFTSTATUS;</span><br><span class="line">		&#125;</span><br><span class="line">		node.leftChild = leftRightChild;</span><br><span class="line">		left.rightChild = node;</span><br><span class="line">		left.parent = node.parent;</span><br><span class="line">		node.parent = left;</span><br><span class="line">		left.status = node.status;</span><br><span class="line">		<span class="keyword">if</span>(node.status == LEFTSTATUS) &#123;</span><br><span class="line">			left.parent.leftChild = left;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(node.status == RIGHTSTATUS)&#123;</span><br><span class="line">			left.parent.rightChild = left;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			root = left;</span><br><span class="line">		&#125;</span><br><span class="line">		node.status = RIGHTSTATUS;</span><br><span class="line">		<span class="keyword">while</span>(node!=null) &#123;</span><br><span class="line">			node.height = Math.max(getHeight(node.leftChild)+1, getHeight(node.rightChild)+1);</span><br><span class="line">			node = node.parent;</span><br><span class="line">		&#125;</span><br><span class="line">		node = left;</span><br><span class="line">		<span class="built_in">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	public int getHeight(Node node) &#123;</span><br><span class="line">		//获得树高，null为-1</span><br><span class="line">		<span class="built_in">return</span> node == null ? -1 : node.height;</span><br><span class="line">	&#125;</span><br><span class="line">	public int getBF(Node node) &#123;</span><br><span class="line">		//获得平衡因子---左子树高-右子树高</span><br><span class="line">		<span class="built_in">return</span>  getHeight(node.leftChild)- getHeight(node.rightChild);</span><br><span class="line">	&#125;</span><br><span class="line">	public void avl(Node parent) &#123;</span><br><span class="line">		<span class="keyword">if</span>(parent == null) &#123;</span><br><span class="line">			<span class="built_in">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			Node left = parent.leftChild;</span><br><span class="line">			Node right = parent.rightChild;</span><br><span class="line">			<span class="keyword">if</span>(getHeight(right)&gt;getHeight(left)+1) &#123;</span><br><span class="line">				leftTransformAndReturn(parent);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span>(getHeight(left)&gt;getHeight(right)+1) &#123;</span><br><span class="line">				rightTransformAndReturn(parent);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				avl(parent.parent);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	public Node addAndReturnParent(Node node,Node parent) &#123;</span><br><span class="line">		<span class="keyword">if</span>(parent == null) &#123;</span><br><span class="line">			root = parent = node;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">if</span>(parent.num&gt;node.num) &#123;</span><br><span class="line">				//right add</span><br><span class="line">				Node right = parent.rightChild;</span><br><span class="line">				<span class="keyword">if</span>(right == null) &#123;</span><br><span class="line">					node.parent = parent;</span><br><span class="line">					node.status = RIGHTSTATUS;</span><br><span class="line">					parent.rightChild = node;</span><br><span class="line">					<span class="keyword">if</span>(parent.leftChild == null) &#123;</span><br><span class="line">						Node temp = parent;</span><br><span class="line">						temp.height++;</span><br><span class="line">						boolean flag = <span class="literal">true</span>;</span><br><span class="line">						<span class="keyword">while</span>((temp=temp.parent)!=null &amp;&amp; flag) &#123;</span><br><span class="line">							int oldHeight = temp.height;</span><br><span class="line">							temp.height = Math.max(getHeight(temp.leftChild)+1, getHeight(temp.rightChild)+1);</span><br><span class="line">							flag = (oldHeight != temp.height);</span><br><span class="line">						&#125;</span><br><span class="line">						avl(parent);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span> &#123;</span><br><span class="line">					addAndReturnParent(node,right);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				//left add</span><br><span class="line">				Node left = parent.leftChild;</span><br><span class="line">				<span class="keyword">if</span>(left == null) &#123;</span><br><span class="line">					node.parent = parent;</span><br><span class="line">					parent.leftChild = node;</span><br><span class="line">					node.status = LEFTSTATUS;</span><br><span class="line">					<span class="keyword">if</span>(parent.rightChild == null) &#123;</span><br><span class="line">						Node temp = parent;</span><br><span class="line">						temp.height++;</span><br><span class="line">						boolean flag = <span class="literal">true</span>;</span><br><span class="line">						<span class="keyword">while</span>((temp=temp.parent)!=null &amp;&amp; flag) &#123;</span><br><span class="line">							int oldHeight = temp.height;</span><br><span class="line">							temp.height = Math.max(getHeight(temp.leftChild)+1, getHeight(temp.rightChild)+1);</span><br><span class="line">							flag = (oldHeight != temp.height);</span><br><span class="line">						&#125;</span><br><span class="line">						avl(parent);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span> &#123;</span><br><span class="line">					addAndReturnParent(node,left);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> parent;</span><br><span class="line">	&#125;</span><br><span class="line">	public Node addNum(int num) &#123;</span><br><span class="line">		Node node = new Node();</span><br><span class="line">		node.num = num;</span><br><span class="line">		addAndReturnParent(node, root);</span><br><span class="line">		<span class="built_in">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	public Node findNum(int num) &#123;</span><br><span class="line">		Node node = root;</span><br><span class="line">		<span class="keyword">while</span>(node!=null) &#123;</span><br><span class="line">			<span class="keyword">if</span>(node.num == num)</span><br><span class="line">				<span class="built_in">break</span>;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span>(node.num&lt;num)</span><br><span class="line">				node = node.leftChild;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">				node = node.rightChild;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="节点删除"><a href="#节点删除" class="headerlink" title="节点删除"></a>节点删除</h3><p>如果要删除节点，此时第一考虑树高，<br>1.如果是叶子节点我们可以直接删除，并调整树<br>2.不是叶子节点，找出一个作为替代的叶子节点，顶替其位置（只需要交换值），把问题变为第一种情况</p>
<p>具体的顶替查找就是，如果其左子树为空则左旋一次，变为叶子节点<br>如果右子树为空则右旋一次，变为叶子结点<br>如果都不为空，根据左右子树高度判断，<br>从高度大的一方查找替代后能保持有序的叶子节点（此处判断主要是为了优化减少旋转的次数，不判断选择一边也不影响，因为最终都会调整）<br>最后删除叶子节点后递归调整树</p>
<p>代码实现<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line">public Node deleteNode(Node node) &#123;</span><br><span class="line">		System.out.println(<span class="string">"delete Node...:"</span>+node);</span><br><span class="line">		<span class="keyword">if</span>(node == null)</span><br><span class="line">			<span class="built_in">return</span> node;</span><br><span class="line">		<span class="keyword">if</span>(getHeight(node)==0) &#123;</span><br><span class="line">			Node parent = node.parent;</span><br><span class="line">			node.parent = null;</span><br><span class="line">			<span class="keyword">if</span>(node == root) &#123;</span><br><span class="line">				root = null;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span>(node.status == LEFTSTATUS) &#123;</span><br><span class="line">				parent.leftChild = null;</span><br><span class="line">				Node temp = parent;</span><br><span class="line">				boolean flag = <span class="literal">true</span>;</span><br><span class="line">				<span class="keyword">while</span>((temp=temp.parent)!=null &amp;&amp; flag) &#123;</span><br><span class="line">					int oldHeight = temp.height;</span><br><span class="line">					temp.height = Math.max(getHeight(temp.leftChild)+1, getHeight(temp.rightChild)+1);</span><br><span class="line">					flag = (oldHeight != temp.height);</span><br><span class="line">				&#125;</span><br><span class="line">				avl(parent);</span><br><span class="line"></span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				parent.rightChild = null;</span><br><span class="line">				Node temp = parent;</span><br><span class="line">				boolean flag = <span class="literal">true</span>;</span><br><span class="line">				<span class="keyword">while</span>((temp=temp.parent)!=null &amp;&amp; flag) &#123;</span><br><span class="line">					int oldHeight = temp.height;</span><br><span class="line">					temp.height = Math.max(getHeight(temp.leftChild)+1, getHeight(temp.rightChild)+1);</span><br><span class="line">					flag = (oldHeight != temp.height);</span><br><span class="line">				&#125;</span><br><span class="line">				avl(parent);</span><br><span class="line">			&#125;</span><br><span class="line">			</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">if</span>(node.leftChild == null) &#123;</span><br><span class="line">				leftTransformAndReturn(node);</span><br><span class="line">				deleteNode(node);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span>(node.rightChild == null) &#123;</span><br><span class="line">				rightTransformAndReturn(node);</span><br><span class="line">				deleteNode(node);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> <span class="keyword">if</span>(getHeight(node.leftChild)&gt;getHeight(node.rightChild)) &#123;</span><br><span class="line">				Node leftSmall = node.leftChild;</span><br><span class="line">				<span class="keyword">while</span>(leftSmall.rightChild!=null) &#123;</span><br><span class="line">					leftSmall = leftSmall.rightChild;</span><br><span class="line">				&#125;</span><br><span class="line">				node.num ^= leftSmall.num;</span><br><span class="line">				leftSmall.num ^= node.num;</span><br><span class="line">				node.num ^= leftSmall.num;</span><br><span class="line">				deleteNode(leftSmall);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span> &#123;</span><br><span class="line">				Node rightBig = node.rightChild;</span><br><span class="line">				<span class="keyword">while</span>(rightBig.leftChild!=null) &#123;</span><br><span class="line">					rightBig = rightBig.leftChild;</span><br><span class="line">				&#125;</span><br><span class="line">				node.num ^= rightBig.num;</span><br><span class="line">				rightBig.num ^= node.num;</span><br><span class="line">				node.num ^= rightBig.num;</span><br><span class="line">				deleteNode(rightBig);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> node;</span><br><span class="line">	&#125;</span><br><span class="line">	public Node deleteNum(int num) &#123;</span><br><span class="line">		Node node = findNum(num);</span><br><span class="line">		<span class="built_in">return</span> deleteNode(node);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/04/03/手撕B树/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          手撕B树
        
      </div>
    </a>
  
  
    <a href="/blog/2019/03/30/java的四种引用类型/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">java的四种引用类型</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="手撕AVL树" data-title="手撕AVL树" data-url="http://eetal.gitee.io/blog/blog/2019/03/31/手撕AVL树/"  data-images="/blog/images/head.jpg" data-content="手撕AVL树">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>